package com.lu.springbootinit.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.springbootinit.common.ErrorCode;
import com.lu.springbootinit.constant.CommonConstant;
import com.lu.springbootinit.exception.BusinessException;
import com.lu.springbootinit.exception.ThrowUtils;
import com.lu.springbootinit.mapper.QuestionBankQuestionMapper;
import com.lu.springbootinit.model.dto.questionBankQuestion.QuestionBankQuestionQueryRequest;
import com.lu.springbootinit.model.entity.Question;
import com.lu.springbootinit.model.entity.QuestionBank;
import com.lu.springbootinit.model.entity.QuestionBankQuestion;
import com.lu.springbootinit.model.entity.User;
import com.lu.springbootinit.model.vo.QuestionBankQuestionVO;
import com.lu.springbootinit.model.vo.UserVO;
import com.lu.springbootinit.service.QuestionBankQuestionService;
import com.lu.springbootinit.service.QuestionBankService;
import com.lu.springbootinit.service.QuestionService;
import com.lu.springbootinit.service.UserService;
import com.lu.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.aop.framework.AopContext;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 题目服务实现
 */
@Service
@Slf4j
public class QuestionBankQuestionServiceImpl extends ServiceImpl<QuestionBankQuestionMapper, QuestionBankQuestion> implements QuestionBankQuestionService {

    @Resource
    private UserService userService;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionBankService questionBankService;

    /**
     * 校验数据
     *
     * @param questionBankQuestion
     * @param add                  对创建的数据进行校验
     */
    @Override
    public void validQuestionBankQuestion(QuestionBankQuestion questionBankQuestion, boolean add) {
        ThrowUtils.throwIf(questionBankQuestion == null, ErrorCode.PARAMS_ERROR);
        //不需要校验
        // todo 从对象中取值
//        String title = questionBankQuestion.getTitle();
//        // 创建数据时，参数不能为空
//        if (add) {
//            // todo 补充校验规则
//            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
//        }
//        // 修改数据时，有参数则校验
//        // todo 补充校验规则
//        if (StringUtils.isNotBlank(title)) {
//            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
//        }
    }

    /**
     * 获取查询条件
     *
     * @param questionBankQuestionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionBankQuestion> getQueryWrapper(QuestionBankQuestionQueryRequest questionBankQuestionQueryRequest) {
        QueryWrapper<QuestionBankQuestion> queryWrapper = new QueryWrapper<>();
        if (questionBankQuestionQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long questionBankId = questionBankQuestionQueryRequest.getQuestionBankId();
        Long questionId = questionBankQuestionQueryRequest.getQuestionId();
        Long id = questionBankQuestionQueryRequest.getId();
        Long notId = questionBankQuestionQueryRequest.getNotId();
        String sortField = questionBankQuestionQueryRequest.getSortField();
        String sortOrder = questionBankQuestionQueryRequest.getSortOrder();
        Long userId = questionBankQuestionQueryRequest.getUserId();
        // todo 补充需要的查询条件
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionBankId), "questionBankId", questionBankId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题目封装
     *
     * @param questionBankQuestion
     * @param request
     * @return
     */
    @Override
    public QuestionBankQuestionVO getQuestionBankQuestionVO(QuestionBankQuestion questionBankQuestion, HttpServletRequest request) {
        // 对象转封装类
        QuestionBankQuestionVO questionBankQuestionVO = QuestionBankQuestionVO
                .objToVo(questionBankQuestion);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = questionBankQuestion.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionBankQuestionVO.setUser(userVO);
        // endregion

        return questionBankQuestionVO;
    }

    /**
     * 分页获取题目封装
     *
     * @param questionBankQuestionPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionBankQuestionVO> getQuestionBankQuestionVOPage(Page<QuestionBankQuestion> questionBankQuestionPage, HttpServletRequest request) {
        List<QuestionBankQuestion> questionBankQuestionList = questionBankQuestionPage.getRecords();
        Page<QuestionBankQuestionVO> questionBankQuestionVOPage =
                new Page<>(questionBankQuestionPage.getCurrent(),
                        questionBankQuestionPage.getSize(),
                        questionBankQuestionPage.getTotal());
        if (CollUtil.isEmpty(questionBankQuestionList)) {
            return questionBankQuestionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionBankQuestionVO> questionBankQuestionVOList =
                questionBankQuestionList.stream().map(questionBankQuestion
                                -> QuestionBankQuestionVO
                                .objToVo(questionBankQuestion))
                        .collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionBankQuestionList
                .stream()
                .map(QuestionBankQuestion::getUserId)
                .collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        questionBankQuestionVOList.forEach(questionBankQuestionVO -> {
            Long userId = questionBankQuestionVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionBankQuestionVO.setUser(userService.getUserVO(user));
        });
        // endregion

        questionBankQuestionVOPage.setRecords(questionBankQuestionVOList);
        return questionBankQuestionVOPage;
    }

    @Override
    public List<Long> getQuestionIdsByQuestionBankId(Long questionBankId) {
        List<Long> questionIds = baseMapper.getQuestionIdsByQuestionBankId(questionBankId);
        return questionIds;
    }

    /**
     * 分小批量添加题目到题库（事务，仅供内部调用）
     *
     * @param questionBankQuestions
     */
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void batchAddQuestionsToBankInner(List<QuestionBankQuestion> questionBankQuestions) {
        // 自信进行批量处理的逻辑代码
        //        for (QuestionBankQuestion questionBankQuestion : questionBankQuestions) {
//            long questionId = questionBankQuestion.getQuestionId();
//            long questionBankId = questionBankQuestion.getQuestionBankId();
//            try {
//                boolean result = this.save(questionBankQuestion);
//                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "向题库添加题目失败");
//            } catch (DataIntegrityViolationException e) {
//                log.error("数据库唯一键冲突或违反其他完整性约束，题目 id: {}, 题库 id: {}, 错误信息: {}",
//                        questionId, questionBankId, e.getMessage());
//                throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目已存在于该题库，无法重复添加");
//            } catch (DataAccessException e) {
//                log.error("数据库连接问题、事务问题等导致操作失败，题目 id: {}, 题库 id: {}, 错误信息: {}",
//                        questionId, questionBankId, e.getMessage());
//                throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据库操作失败");
//            } catch (Exception e) {
//                // 捕获其他异常，做通用处理
//                log.error("添加题目到题库时发生未知错误，题目 id: {}, 题库 id: {}, 错误信息: {}",
//                        questionId, questionBankId, e.getMessage());
//                throw new BusinessException(ErrorCode.OPERATION_ERROR, "向题库添加题目失败");
//            }
//        }
        //MyBatisPlus提供的批量插入方法，可以自动处理事务和数据完整性约束
        try {
            boolean result = this.saveBatch(questionBankQuestions);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "向题库添加题目失败");
        } catch (DataIntegrityViolationException e) {
            log.error("数据库唯一键冲突或违反其他完整性约束, 错误信息: {}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目已存在于该题库，无法重复添加");
        } catch (DataAccessException e) {
            log.error("数据库连接问题、事务问题等导致操作失败, 错误信息: {}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据库操作失败");
        } catch (Exception e) {
            // 捕获其他异常，做通用处理
            log.error("添加题目到题库时发生未知错误，错误信息: {}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "向题库添加题目失败");
        }
    }


    /**
     * 批量添加题目到题库
     *
     * @param questionIds
     * @param questionBankId
     * @param loginUser
     */
    @Async
    @Override
    public void batchAddQuestionToBank(List<Long> questionIds, Long questionBankId, User loginUser) {
        //参数校验
        ThrowUtils.throwIf(CollUtil.isEmpty(questionIds), ErrorCode.PARAMS_ERROR, "题目列表为空");
        ThrowUtils.throwIf(questionBankId <= 0 || questionBankId == null, ErrorCode.PARAMS_ERROR, "题库 id 不能空");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        //数据校验

        //检查题目 id 是否存在
        LambdaQueryWrapper<Question> questionLambdaQueryWrapper = Wrappers.lambdaQuery(Question.class)
                .select(Question::getId)
                .in(Question::getId, questionIds);
        //检查题库 id 是否存在
        QuestionBank questionBank = questionBankService.getById(questionBankId);
        ThrowUtils.throwIf(questionBank == null, ErrorCode.PARAMS_ERROR, "题库不存在");

        //合法的 id 列表
        Set<Long> validQuestionIdSet = questionService.listObjs(questionLambdaQueryWrapper, obj -> (Long) obj).stream().collect(Collectors.toSet());
        ThrowUtils.throwIf(CollUtil.isEmpty(validQuestionIdSet), ErrorCode.PARAMS_ERROR, "合法的题目列表为空");

        //检查哪些题目还不存在于题库中
        //先查题库下的题目列表
        LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                .eq(QuestionBankQuestion::getQuestionBankId, questionBankId)
                .in(QuestionBankQuestion::getQuestionId, validQuestionIdSet)
                .select(QuestionBankQuestion::getQuestionId);
        List<Long> ExitQuestionList = this.listObjs(lambdaQueryWrapper, obj -> (Long) obj);
        //把已经是题库下的题目id从validQuestionIdSet中移除
        List<Long> validQuestionIdList = validQuestionIdSet.stream()
                .filter(id -> !ExitQuestionList.contains(id))
                .collect(Collectors.toList());
        ThrowUtils.throwIf(CollUtil.isEmpty(validQuestionIdList), ErrorCode.PARAMS_ERROR, "所有题目都在选中的题库当中");

        // 自定义线程池
        ThreadPoolExecutor customExecutor = new ThreadPoolExecutor(
                20,     //核心线程数
                50,                //最大线程数
                60,                //线程存活时间
                TimeUnit.SECONDS,  //时间单位
                new ArrayBlockingQueue<>(100000),   //阻塞队列容量
                new ThreadPoolExecutor.CallerRunsPolicy()  //拒绝策略
        );
        // 保存所有批次任务
        List<CompletableFuture<Void>> futures = new ArrayList<>();

        // 分批处理，避免长事务，假设每次处理 1 k 条数据
        int batchSize = 1000;
        int totalQuestionListSize = validQuestionIdList.size();
        validQuestionIdList.stream().collect(Collectors.toList());
        for (int i = 0; i < totalQuestionListSize; i += batchSize) {
            //生成每批次的数据
            List<Long> subList = validQuestionIdList.subList(i, Math.min(i + batchSize, totalQuestionListSize));
            List<QuestionBankQuestion> questionBankQuestionSubList = subList.stream().map(questionId -> {
                QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
                questionBankQuestion.setQuestionBankId(questionBankId);
                questionBankQuestion.setQuestionId(questionId);
                questionBankQuestion.setUserId(loginUser.getId());
                return questionBankQuestion;
            }).collect(Collectors.toList());
            //使用事务处理每批次的数据
            //事务代理对象
            QuestionBankQuestionServiceImpl questionBankQuestionService = (QuestionBankQuestionServiceImpl) AopContext.currentProxy();
            // questionBankQuestionService.batchAddQuestionsToBankInner(questionBankQuestionSubList);
            //异步处理每批数据，将任务添加到异步任务列表
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                try {
                    questionBankQuestionService.batchAddQuestionsToBankInner(questionBankQuestionSubList);
                } catch (Exception e) {
                    log.error("批量添加题目到题库时发生异常，异常信息：{}", e.getMessage());
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量添加题目到题库时发生异常");
                }
            }, customExecutor);
            futures.add(future);
        }
        //循环等待所有的异步任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        //关闭线程池
        customExecutor.shutdown();
    }

    /**
     * 批量从题库移除题目
     *
     * @param questionIds
     * @param questionBankId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchRemoveQuestionToBank(List<Long> questionIds, Long questionBankId) {
        //参数校验
        ThrowUtils.throwIf(CollUtil.isEmpty(questionIds), ErrorCode.PARAMS_ERROR, "题目列表为空");
        ThrowUtils.throwIf(questionBankId <= 0 || questionBankId == null, ErrorCode.PARAMS_ERROR, "题库 id 不能空");
        //执行删除关联
        for (Long questionId : questionIds) {
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                    .eq(QuestionBankQuestion::getQuestionId, questionId)
                    .eq(QuestionBankQuestion::getQuestionBankId, questionBankId);
            boolean remove = this.remove(lambdaQueryWrapper);
            ThrowUtils.throwIf(!remove, ErrorCode.OPERATION_ERROR, "从题库移除题目失败");
        }
    }
}
